package com.tbit.uqbike.webmanager.sms;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;

/**
 * Created on 17/6/7.
 * 短信API产品的DEMO程序,工程中包含了一个SmsDemo类，直接通过
 * 执行main函数即可体验短信产品API功能(只需要将AK替换成开通了云通信-短信产品功能的AK即可)
 * 工程依赖了2个jar包(存放在工程的libs目录下)
 * 1:aliyun-java-sdk-core.jar
 * 2:aliyun-java-sdk-dysmsapi.jar
 * <p>
 * 备注:Demo工程编码采用UTF-8
 * 国际短信发送请勿参照此DEMO
 */
@Slf4j
public class ApiAliyunSms {
    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    public static void sendSms(String accessKeyId, String accessKeySecret, String productname, String templateCode, String phone, String code) {
        log.info("短信验证码phone=" + phone + ",code=" + code);
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", domain);
        } catch (ClientException e) {
            log.error("连接阿里云短信服务异常", e);
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setSignName(productname);
        request.setTemplateCode(templateCode);
        if (code != null) {
            request.setTemplateParam("{\"code\":\"" + code + "\"}");
        }

        SendSmsResponse sendSmsResponse = null;
        ;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (Exception e) {
            log.error("连接阿里云短信服务异常", e);
        }

        /**发送短信失败错误打印*/
        if (sendSmsResponse == null) {
            log.error("短信发送失败,phone=" + phone + "code=" + code);
            return;
        }
        if (!"OK".equals(sendSmsResponse.getMessage())) {
            log.error("阿里云短信错误信息=" + sendSmsResponse.getMessage());
        }
    }
}
